#
# ai.py -- AI class for ship control
# 
# author: Tom "Knio" Flanagan
#         knio@h4xn3t.net
#         theknio@gmail.com
#         irc.freenode.net - Knio - #python #pygame #py
#
# this file released under Public Domain
#


from object import Vector
import object
import ship
import weapon
from constants import *


class Ai:
    def __init__(self, ship, battle):
        self.ship = ship
        self.battle = battle

    def parse_data(self, data):
        self.any = []
        self.targets = []
        self.enemies  = []
        self.friends = []
        self.objects = []
        self.deaders = []
        for [d], o in data:
            self.any.append((d, o))
            if  o.state == 0:                   self.deaders.append((d, o))
            elif not isinstance(o, ship.Ship):  self.objects.append((d, o))
            elif o.team == self.ship.team:      self.friends.append((d, o))
            else:
                self.enemies. append((d, o))
                if self.ship.mintarg <= o.size <= self.ship.maxtarg:
                    self.targets.append((d, o))
                    
        self.nearest_target = (self.targets and self.targets[0][1]) or None
        self.nearest_enemy  = (self.enemies and self.enemies[0][1]) or None
        self.nearest_friend = (self.friends and self.friends[0][1]) or None
        self.nearest_object = (self.objects and self.objects[0][1]) or None
        self.nearest_deader = (self.deaders and self.deaders[0][1]) or None
        
    def tick(self, data):
        self.data = self.parse_data(data)
        self.ship.target = object.Vector(self.nearest_target or self.nearest_enemy or 0, a=self.ship.maxa)
        t = self.targets
        t.extend(self.enemies)
        for i in self.ship.weapons:
            self.attack(i, [n for i,n in t])

    def attack(self, wepn, targets):
        for i in targets:
            wepn.attack(i)

    def hit(self, weapon, damage):
        pass

    def die(self, damage):
        pass
